package com.ww.springboot.boot.javabase.proxy.cglib;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.LazyLoader;

public class EnhancerLazyLoader {

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            CarFactory factory = new CarFactory();
            System.out.println("factory built");
            System.out.println("-----");
            //只有第一次才会触发(每次创建对象 只有第一次触发 实际场景可能会用到)
            System.out.println(factory.car.getName());
            System.out.println("-----");
            System.out.println(factory.car.getName());
        }
    }

    static class Car {
        String name;

        Car() {
        }

        String getName() {
            return name;
        }
    }

    static class CarFactory {
        Car car;

        CarFactory() {
            car = carLazyProxy();
        }

        Car carLazyProxy() {
            //只有第一次才会触发
            return (Car) Enhancer.create(Car.class, (LazyLoader) () -> {
                System.out.println("prepare loading");
                Car car = new Car();
                car.name = "this is a car";
                System.out.println("after loading");
                return car;
            });
        }
    }
}